<?php
/**
 * mysql数据库单例类
 * 缺点是
 */
class Db {
	static private $_instance;
	static private $_connect;
	private $_config = array(
		'host' => '127.0.0.1',    //主机地址
		'user' => 'root',         //用户名
		'password' => '',         //密码
		'database' => 'video',    //数据库
	);
  //私有的构造方法
	private function __construct() {
	}
  //访问实例的public方法
	static public function createInstance($config) {
    
    if(is_array($config) 
      && array_key_exists ('host', $config) 
      && array_key_exists ('user', $config)
      && array_key_exists ('password', $config) 
      && array_key_exists ('database', $config)
      ){
      //获取数据库配置    
      self::$_config = $config;
      
      //实例化数据库类
      if(!(self::$_instance instanceof self)) {
        self::$_instance = new self();
      }
      return self::$_instance;
    }else{
      die('DB param error.');
    }
	}
  //访问实例的public方法
	static public function getInstance() {
		if(!(self::$_instance instanceof self)) {
			self::$_instance = new self();
		}
		return self::$_instance;
	}
  //连接数据库
	public function connect() {
		if(!self::$_connect) {
			self::$_connect = @mysql_connect($this->_config['host'], $this->_config['user'], $this->_config['password']);	

			if(!self::$_connect) {
				throw new Exception('mysql connect error ' . mysql_error());
				//die('mysql connect error' . mysql_error());
			}
			
			mysql_select_db($this->_config['database'], self::$_connect);
			mysql_query("set names UTF8", self::$_connect);
		}
		return self::$_connect;
	}
}
/*
$connect = Db::getInstance()->connect();
$sql = "select * from video";
$result = mysql_query($sql, $connect);
echo mysql_num_rows($result);
var_dump($result);
*/